package com.green.card.smscode;

import android.content.Context;

import com.google.gson.Gson;
import com.green.card.R;
import com.green.card.bean.SMSResultBean;
import com.green.card.constants.Config;
import com.green.card.utils.PackegeIdUtils;
import com.green.card.utils.ZYALogUtils;
import com.zhuoyian.analysis.util.EncodeUtil;
import com.zyasdk.util.SP;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by admin on 2018/1/30.
 * @des 第一家短信验证码  http://www.17int.cn/msg/
 */

public class FirstSmsCode {
    /**
     * 使用SP保存到本地的唯一批处理的ID
     */
    private static final String BATCHID = Config.BATCHID;

    private static int    mSmsCode;//短信验证码
    private static String mBatchId;// 系统生成的唯一批处理ID

    public static int getmSmsCode() {
        return mSmsCode;
    }

    /**
     * 发送请求获取短信验证码
     * @param phoneNumber
     *          手机号码
     */
    public static void sendVerificationCode(final Context context, String phoneNumber) {
        try {
            //短信验证码
            mSmsCode = getSmsCode();
            OkHttpClient client = new OkHttpClient();
            String account = "s11120001";//用户帐号，由系统管理员提供
            String password = "E99A18C428CB38D5F260853678922E03";//用户帐号对应的密码，由系统管理员提供
            String mobile = phoneNumber;//发送的目的号码
            String content = EncodeUtil.decoderUTF8("【卓易安科技】您好，您的验证是"+ mSmsCode +"，请妥善保管");//短信的内容，内容需要UTF-8编码
            String requestId = PackegeIdUtils.getRawFileContent(context.getApplicationContext(), R.raw.p);//唯一的用户请求ID, 服务器不检查唯一性，只作记录。

            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("account", account);
            jsonObject.put("password", password);
            jsonObject.put("mobile", mobile);
            jsonObject.put("content", content);
            jsonObject.put("requestId",requestId);
            String json = jsonObject.toString();
            ZYALogUtils.i("json-->"+json);
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(Config.SMS_URL)
                    .addHeader("Content-Type","application/json; charset=utf-8")
                    .header("Accept", "application/json")
                    .post(body)
                    .build();
            Call call = client.newCall(request);
            // 这里是测试使用，代码可删除
           /* parseJsonObject("{\n" +
                    "\n" +
                    "    \"requestId\": \"1234567890\",\n" +
                    "\n" +
                    "    \"status\": \"10\",\n" +
                    "\n" +
                    "    \"batchId\": \"1075\",\n" +
                    "\n" +
                    "    \"errorCode\": \"ALLSuccess\"\n" +
                    "\n" +
                    "}");*/

            //异步请求短信验证码平台
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    ZYALogUtils.e("短信平台请求-->"+e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    ZYALogUtils.d("短信平台result-->"+result);
                    parseJsonObject(context,result);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析返回的json数据
     * @param result
     *      成功请求返回的数据
     */
    private static void parseJsonObject(Context context,String result) {
        Gson gson = new Gson();
        SMSResultBean smsResultBean = gson.fromJson(result, SMSResultBean.class);
        String errorCode = smsResultBean.errorCode;
        ZYALogUtils.d("errorCode-->"+errorCode);
        if ("ALLSuccess".equals(errorCode)){// 请求成功
            // 系统生成的唯一批处理ID
            mBatchId = smsResultBean.batchId;
            // 保存到本地
            SP.put(context,BATCHID, mBatchId);
        }
    }

    /**
     * 返回自定义的验证码，6位数据
     * @return
     */
    private static int getSmsCode(){
        int smsCode = (int) ((Math.random()*9+1)*100000);
        return smsCode;
    }
}
